//
//  FlowerViewController.m
//  KoreaFlower
//
//  Created by Nicejinux on 12. 11. 11..
//  Copyright (c) 2012년 Nicejinux. All rights reserved.
//

#import "GlobalDefine.h"
#import "DBSQLQueries.h"
#import "DBManager.h"
#import "FlowerViewController.h"
#import "ListViewCell.h"
#import "DetailViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface FlowerViewController ()
{
    bool isOpend;
    bool isDragging;
    bool listViewShown;
    int  currentCategoryIndex;
}
@property (nonatomic, strong) MenuViewController *menuViewController;
@property (nonatomic, strong) StreamViewController *streamViewController;
@property (nonatomic, strong) DetailViewController *detailViewController;

@end

@implementation FlowerViewController

@synthesize dataSrc;
@synthesize listTableView, categoryView, mainView, streamView, listView, naviView;
@synthesize menuViewController, streamViewController, detailViewController;
@synthesize titleLabel, titleShadowLabel;
@synthesize tabBarView;
@synthesize refreshView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"상품보기";
        self.tabBarItem.image = [UIImage imageNamed:@"0073"];
        
        isOpend = NO;
        isDragging = NO;
        listViewShown = NO;
        currentCategoryIndex = 0;
    }
    
    return self;
}

- (id)initWithNibNameWithList:(NSString *)nibNameOrNil List:(NSArray *)list bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"상품보기";
        self.tabBarItem.image = [UIImage imageNamed:@"0073"];
        self.dataSrc = [NSMutableArray arrayWithArray:list];
        isOpend = NO;
        listViewShown = NO;
    }
    
    return self;
}

- (IBAction)changeList:(id)sender
{
    if (isOpend) {
        [self closeMenu];
    }
    else {

        [self closed];
    }
}

- (void)closed
{
    [UIView beginAnimations:@"begin" context:nil];
    [UIView setAnimationDuration:1];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    if (!listViewShown) {
        [self.mainView bringSubviewToFront:streamView];
        listViewShown = YES;
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
    }
    else
    {
        [self.mainView bringSubviewToFront:listView];
        listViewShown = NO;
        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
    }
    
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

- (void)closeMenu
{
    [UIView beginAnimations:@"begin" context:nil];
    [UIView setAnimationDuration:0.25];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDidStopSelector:@selector(closed)];
    
    if (isOpend) {
        self.mainView.frame = CGRectMake(0, self.mainView.frame.origin.y, self.mainView.frame.size.width, self.mainView.frame.size.height);
        isOpend = NO;
    }
    
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

- (void) showMenu
{
    [UIView beginAnimations:@"begin" context:nil];
    [UIView setAnimationDuration:0.25];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    
    if (!isOpend) {
        self.mainView.frame = CGRectMake(LEFT_MENU_POS, self.mainView.frame.origin.y, self.mainView.frame.size.width, self.mainView.frame.size.height);
        isOpend = YES;
    }
    else {
        self.mainView.frame = CGRectMake(0, self.mainView.frame.origin.y, self.mainView.frame.size.width, self.mainView.frame.size.height);
        isOpend = NO;
    }
    
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

- (IBAction)showMenu:(id)sender
{
    [self showMenu];
}

- (void)finishLoad
{
    [self reloadTableData:currentCategoryIndex];
    [listTableView setContentOffset:CGPointMake(0, 0)];
//    [listTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
//    if (dataSrc == nil) {
//        dataSrc = [[NSMutableArray alloc] initWithCapacity:10];
//    }
    
    //refresh 뷰 설정
    self.refreshView = [[RefreshView alloc] initWithFrame:CGRectMake(0, -60, 320, 60)];
    refreshView.delegate = self;
    [listTableView addSubview:refreshView];

    [self.navigationController.navigationBar setHidden:YES];
    [titleLabel setText:@"전체보기"];
    
    menuViewController = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil];
    [self.categoryView addSubview:menuViewController.view];
    menuViewController.delegate = self;
    
    streamViewController = [[StreamViewController alloc] initWithNibName:@"StreamViewController" bundle:nil];
    [self.streamView addSubview:streamViewController.view];
    streamViewController.delegate = self;

    [self drawShadow];
}

- (void)drawShadow
{
    mainView.layer.shadowColor = [UIColor blackColor].CGColor;
    mainView.layer.shadowOpacity = 0.7f;
    mainView.layer.shadowOffset = CGSizeMake(-5.0f, 0);
    mainView.layer.shadowRadius = 4.0f;
    mainView.layer.masksToBounds = NO;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:mainView.bounds];
    mainView.layer.shadowPath = path.CGPath;
}

- (void)viewDidUnload
{
    [self setListTableView:nil];
    [self setCategoryView:nil];
    [self setStreamView:nil];
    [self setListView:nil];
    [self setTitleLabel:nil];
    [self setNaviView:nil];
    [self setMainView:nil];
    [self setTitleShadowLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (void)setNaviTitle:(NSString *)title
{
    [titleLabel setText:title];
    [titleShadowLabel setText:title];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 105;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSLog(@"%@", dataSrc);
    return [dataSrc count];
}

//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    static NSString *CellIdentifier = @"Cell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//
//    // Configure the cell...
//
//    return cell;
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ListViewCell";
    ListViewCell *cell = (ListViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed:@"ListViewCell" owner:nil options:nil];
        cell = [arr objectAtIndex:0];
    }
    
    if (![dataSrc count]) {
        return cell;
    }
    [cell setProductListCell:[dataSrc objectAtIndex:indexPath.row] tabIndex:0 cellIndex:indexPath.row];

    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
    [self pushToDetailView:indexPath.row];
}

- (void)streamViewDidSelected:(int)index
{
    [self pushToDetailView:index];
}

- (void)reloadTableData:(int)index
{
    NSString *sql;
    currentCategoryIndex = index;
    
    if (index == 0) {
        sql = SELECT_FlowerInfoList_All;
    }
    else
    {
        sql = [NSString stringWithFormat:SELECT_FlowerInfoList_BySaleCate, index];
    }

    NSMutableArray *list = [[DBManager sharedInstance] executeSelectQuery:sql];
    [dataSrc removeAllObjects];
    dataSrc = list;
    
    [listTableView reloadData];
    [listTableView setContentOffset:CGPointMake(0, 0)];
}

- (void)menuTableViewDidSelected:(NSIndexPath *)indexPath WithTitle:(NSString *)title
{
    [self showMenu];
    [self setNaviTitle:title];
    [self reloadTableData:indexPath.row];
}

- (void)pushToDetailView:(int)index
{
    detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailViewController.indexLabelString = [[dataSrc objectAtIndex:index] objectForKey:@"saleCategoryName"];
    detailViewController.titleLabelString = [[dataSrc objectAtIndex:index] objectForKey:@"flowerName"];
    detailViewController.detailDic = [dataSrc objectAtIndex:index];
    //[detailViewController.navigationController setNavigationBarHidden:NO];
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailViewController animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    refreshView.isRequestCancel = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - scrollview delegate methods
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if ([refreshView isLoading]) return;
    isDragging = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
        if ([refreshView isLoading]) {
            // Update the content inset, good for section headers
            if (scrollView.contentOffset.y > 0) {
                listTableView.contentInset = UIEdgeInsetsZero;
            }
            else if (scrollView.contentOffset.y >= -refreshView.refreshHeaderHeight) {
                listTableView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
            }
        }
        else if (isDragging && scrollView.contentOffset.y < 0) {
            // Update the arrow direction and label
            [UIView beginAnimations:nil context:NULL];
            if (scrollView.contentOffset.y < -refreshView.refreshHeaderHeight) {
                [refreshView setRefreshViewLabel:1];
            } else { // User is scrolling somewhere within the header
                [refreshView setRefreshViewLabel:0];
            }
            [UIView commitAnimations];
        }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if ([refreshView isLoading]) return;
    isDragging = NO;
    if (scrollView.contentOffset.y <= -refreshView.refreshHeaderHeight) {
        // Released above the header
        [refreshView startLoading];
    }
}

@end
